package com.dsit.sq;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import protocol.ProtoFilter;

/**
 * 通信协议消息分发类 通过这个类将数据转发到对应的数据显示界面
 * Created by Administrator on 2016/11/30.
 */

public class ProtoMsgDispatcher implements ProtoFilter.OnFilterResultListener{
    static ProtoMsgDispatcher instance = new ProtoMsgDispatcher();
    private ProtoMsgDispatcher(){}
    List<DataListener> dataListeners = new ArrayList<>();
    Handler handler = new Handler(Looper.myLooper());


    public static ProtoMsgDispatcher getInstance(){
        return instance;
    }

    public void addDataListener(DataListener dl){
        synchronized (dataListeners){
            dataListeners.add(dl);
        }
    }

    public void removeDataListener(DataListener dl){
        synchronized (dataListeners){
            dataListeners.remove(dl);
        }
    }

    int receiverCount = 0;

    public void notifyDataReceive(final ProtoMessage msg){
        synchronized (dataListeners){
            handler.post(new Runnable() {
                @Override
                public void run() {

                    for(int i=0;i<dataListeners.size();i++){
                        if(dataListeners.get(i)!=null){
                            dataListeners.get(i).onUpdateData(msg);
                        }
                    }
                }
            });
        }
    }

    @Override
    public void OnMessageReceive(ByteBuffer bb) {
        System.out.println("====> head:" +bb.getShort());
        System.out.println("---- total_len:" +bb.getInt());
        System.out.println("---- msg_type:" +bb.getInt());
        System.out.println("---- msg_id:" +bb.getLong());

        int action_len = bb.getInt();
        System.out.println("---- action_len:" +action_len);
        byte[] str_byte= new byte[action_len];
        bb.get(str_byte, 0, action_len);
        String action_string = new String(str_byte);
        System.out.println("action string:"+new String(str_byte));

        int data_len = bb.getInt();
        System.out.println("---- data_len:" +data_len);
        byte[] data_byte= new byte[data_len];
        bb.get(data_byte, 0, data_len);
//        System.out.println("data string:"+new String(data_byte));

        ProtoMessage msg = new ProtoMessage(action_string,data_byte);
        if(msg.getActionId().equals("dev.heartbeat")){
            notifyDataReceive(msg);
        }else {
            receiverCount++;
            if (receiverCount == 10) {
                notifyDataReceive(msg);
                receiverCount = 0;
            }
        }
    }
}
